package com.jml.jdk8.stream;


import org.junit.Test;

/**
 * @author:jml
 * @date: 2020/2/25 0025 16:50
 * @description：
 */
public class AutoCloseableTest implements AutoCloseable {

    public void doSomeThing() throws Exception {
        System.out.println("doSomething invoked!");
        throw new Exception();
    }

    @Override
    public void close() throws Exception {
        System.out.println("关闭！");
    }

    @Test
    public void tt() throws Exception {
        //当代码块退出的时候，会自动调用close方法
        //对资源管理来说，可以用这种代替try catch，更优雅的关流关闭资源
        try (AutoCloseableTest autoCloseableTest = new AutoCloseableTest()){
            autoCloseableTest.doSomeThing();
        }
    }

    @Test
    public void t1() throws Exception {
        AutoCloseableTest autoCloseableTest = null;
        try {
            autoCloseableTest = new AutoCloseableTest();
            autoCloseableTest.doSomeThing();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            autoCloseableTest.close();
        }
    }
}
